import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api"
import { setToken, getToken, removeToken } from '@/utils/token.js'

const state = {
  code: '',
  token: getToken (),
  userInfo: {}
}
const mutations = {
  GETCODE (state, code) {
    state.code = code
  },
  USERLOGIN (state, token) {
    state.token = token
  },
  GETUSERINFO (state, userInfo) {
    state.userInfo = userInfo
  },
  CLEAR (state) {
    // 清空仓库中用户信息  清除本地token
    state.token = ''
    state.userInfo = {}
    removeToken ()
  }
}
const actions = {
  // 获取注册验证码
  async getCode (context, phone) {
    // 这个请求把验证码返回了，正常是后台把验证码发送到手机
    const {data: res} = await reqGetCode (phone)
    if (res.code == 200) {
      context.commit ('GETCODE', res.data)
      return 'ok'
    } else {
      return Promise.reject (new Error ('faile'))
    }
  },

  // 完成注册请求
  async userRegister (context, user) {
    const {data: res} = await reqUserRegister (user)
    if (res.code == 200) {
      return 'ok'
    } else {
      return Promise.reject (new Error ('faile'))
    }
  },

  // 登录业务token
  async userLogin (context, data) {
    const {data: res} = await reqUserLogin (data)
    if (res.code == 200) {
      context.commit ('USERLOGIN', res.data.token)
      // 持久化存储token
      setToken (res.data.token)
      return 'ok'
    } else {
      return Promise.reject (new Error ('faile'))
    }
  },

  // 获取用户信息
  async getUserInfo (context) {
    const {data: res} = await reqUserInfo ()
    if (res.code == 200) {
      context.commit ('GETUSERINFO', res.data)
      return 'ok'
    } else {
      return Promise.reject (new Error ('faile'))
    }
  },

  // 退出登录
  async userLogout (context) {
    const {data: res} = await reqLogout ()
    if (res.code == 200) {
      context.commit ('CLEAR')
      return 'ok'
    } else {
      return Promise.reject (new Error ('faile'))
    }
  }
}

 
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}